#include "myNode.h"

myNode::myNode()
{
	heardPostRequest =  new  ofx::HTTP::PostRequest(this->heardURL, Poco::Net::HTTPMessage::HTTP_1_1);
}

myNode::~myNode()
{
	if(imagePostRequest!=NULL)
	{
		delete(imagePostRequest);
		imagePostRequest = NULL;
	}
	if(heardPostRequest!=NULL)
	{
		delete(heardPostRequest);
		heardPostRequest = NULL;
	}
	
}

myNode::myNode(int imageFlame, int heardFlame, std::string nodeId, std::string updataImageURL, std::string heardURL)
{

	this->imageFlame = imageFlame;
	this->heardFlame = heardFlame;
	this->nodeId = nodeId;
	this->updataImageURL = updataImageURL;
	this->heardURL = heardURL;
	
	heardPostRequest = new  ofx::HTTP::PostRequest(this->heardURL, Poco::Net::HTTPMessage::HTTP_1_1);
}

bool myNode:: sendHeard()
{
	if(flagHeard ==false)
	{ 
		flagHeard = true;
		this->heardPostRequest->addFormField("nodeId", this->nodeId);
		this->heardPostRequest->addFormField("access_token", this->accessToken);
	}
	else
	{
		this->heardPostRequest->setFormField("nodeId", this->nodeId);
		this->heardPostRequest->setFormField("access_token", this->accessToken);
	}

	try
	{
		std::istream& responseStream = client.execute(*this->heardPostRequest,
			response,
			context);
		std::cout << "============";
		Poco::StreamCopier::copyStream(responseStream, std::cout);
		std::cout << "============";
		return true;
	}
	catch (const Poco::Exception& exc)
	{
		ofLogError("ofApp::update") << "Got Exception " << exc.displayText() << " " << exc.code();
		return false;
	}
	catch (...)
	{
		ofLogError("ofApp::update") << "Got unknown exception.";
		return false;
	}
}

bool myNode::sendImage(std::string fileName)
{
	if (imagePostRequest != NULL)
	{
		delete(imagePostRequest);
	}
		imagePostRequest = new  ofx::HTTP::PostRequest(this->updataImageURL, Poco::Net::HTTPMessage::HTTP_1_1);
		this->imagePostRequest->addFormField("nodeId", this->nodeId);
		this->imagePostRequest->addFormFile("files", fileName, "DEFAULT_MEDIA_TYPE");
	

	try
	{
		std::istream& responseStream = client.execute(*this->imagePostRequest,
			response,
			context);
		std::cout << "============";
		Poco::StreamCopier::copyStream(responseStream, std::cout);
		std::cout << "============";
		return true;
	}
	catch (const Poco::Exception& exc)
	{
		ofLogError("ofApp::update") << "Got Exception " << exc.displayText() << " " << exc.code();
		return false;
	}
	catch (...)
	{
		ofLogError("ofApp::update") << "Got unknown exception.";
		return false;
	}
}